<?php

namespace app\common\service\ai;

use think\facade\Db;
use app\common\service\CommonService;
use app\common\service\utils\FFmpeg;

/**
 * AI视频
 */
class AiVideoService extends CommonService {

    /**
     * 表名
     * @static string
     */
    protected static $table = 'ai_video';

    /**
     * 列表
     * @param array $data 数据
     * @return array
     */
    public static function getList($data) {
        $list = self::query(self::$table)
                ->leftJoin('order o', 'o.video_id = a.id')
                ->leftJoin('video v', 'v.id = a.video_id')
                ->_equal('a.member_id#member_id')
                ->order('a.id desc')
                ->field('a.*,v.title,o.order_no')
                ->_page();
        return $list;
    }

    /**
     * 列表
     * @param array $data 数据
     * @return array
     */
    public static function getListByHome($data) {
        $list = self::query(self::$table)
                ->leftJoin('order o', 'o.video_id = a.id')
                ->leftJoin('video v', 'v.id = a.video_id')
                ->_equal('a.member_id#member_id')
                ->order('a.id desc')
                ->field('a.*,v.title,o.order_no')
                ->_page(true);
        return $list;
    }

    /**
     * 生成
     * @param array $data 数据
     * @return mixed
     */
    public static function build($data) {
        Db::startTrans();
        // 视频
        $video_id = $data['video_id'] ?? 0;
        if (!$video_id) {
            $video_data = [
                'member_id' => $data['member_id'],
                'url' => $data['video_url'],
                'cover' => str_replace(".mp4", "_0.jpg", $data['video_url']),
            ];
            $video_id = self::model()->_insert('video', $video_data);
            if (!$video_id) {
                Db::rollback();
                exception();
            }
        }
        // 音频
        $voice_id = $data['voice_id'] ?? 0;
        if (!$voice_id && $data['type'] == 0) { // 用户上传
            $voice_data = [
                'member_id' => $data['member_id'],
                'url' => $data['voice_url'],
            ];
            $voice_id = self::model()->_insert('ai_voice', $voice_data);
            if (!$voice_id) {
                Db::rollback();
                exception();
            }
        }
        // 音色
        $speaker_id = $data['speaker_id'] ?? 0;
        // AI视频
        $order_no = OrderService::createOrerNo();
        $ai_video_url = null;
        $ai_video_data = [
            'member_id' => $data['member_id'],
            'url' => $ai_video_url,
            'video_id' => $video_id,
            'voice_id' => $voice_id,
            'speaker_id' => $speaker_id,
            'type' => $data['type'],
            'subtitle' => $data['subtitle'] ?? null,
            'subtitle_font' => $data['subtitle_font'] ?? null,
            'order_no' => $order_no,
        ];
        $ai_video_id = self::model()->_insert('ai_video', $ai_video_data);
        if (!$ai_video_id) {
            Db::rollback();
            exception();
        }
        // 订单
        $point = 0;
        $second_rate = SystemConfigService::getDetail('SECOND_RATE')['value'] ?? 0;
        if (isset($data['video_id'])) {
            $url = self::query('video')->where(['id' => $video_id])->_value('url');
//            $local_url = './' . strstr($url, 'storage');
//            $second = FFmpeg::getDurationByID3($local_url);
            $second = FFmpeg::getDurationFormUrl($url);

            !is_numeric($second) && self::error($second);
            $point = $second * $second_rate;
        } else {
            $second = FFmpeg::getDurationFormUrl($data['video_url']);
            !is_numeric($second) && self::error($second);
            $point = $second * $second_rate;
        }
        $member_point = self::query('member')->where(['member_id' => $data['member_id']])->_value('remain_point');
        $member_point < $point && exception('会员点数不够');
        $order_data = [
            'order_no' => $order_no,
            'status' => 1,
            'member_id' => $data['member_id'],
            'video_id' => $ai_video_id,
            'ai_type' => 0,
            'type' => 2,
            'scene_type' => 1,
            'point' => $point,
            'before_point' => $member_point,
            'after_point' => $member_point - $point,
            'remark' => OrderService::getRemark(2, 1),
        ];
        $order_id = self::model()->_insert('order', $order_data);
        if (!$order_id) {
            Db::rollback();
            exception();
        }
        // 用户扣点
        $result = self::model()->_update('member', ['remain_point' => Db::raw("remain_point-{$point}")], ['member_id' => $data['member_id']]);
        if (!$result) {
            Db::rollback();
            exception();
        }
        Db::commit();
        return success();
    }

    /**
     * 删除
     * @param array $data 数据
     * @return mixed
     */
    public static function del($data) {
        $result = self::model()->_delete(self::$table, self::ID($data));
        !$result && exception();
        return success();
    }
	
	/**
     * 点数
     * @param array $data 数据
     * @return mixed
     */
    public static function getPoint($data) {
		$video_id = $data['video_id'] ?? 0;
		$point = 0;
        $second_rate = SystemConfigService::getDetail('SECOND_RATE')['value'] ?? 0;
        if (isset($data['video_id'])) {
            $url = self::query('video')->where(['id' => $video_id])->_value('url');
            $local_url = './' . strstr($url, 'storage');
//            $second = FFmpeg::getDurationByID3($local_url);
//            !is_numeric($second) && self::error($second);
//            $point = $second * $second_rate;
            $second = FFmpeg::getDurationFormUrl($url);
            !is_numeric($second) && self::error($second);
            $point = $second * $second_rate;
        } else {
            $second = FFmpeg::getDurationFormUrl($data['video_url']);
            !is_numeric($second) && self::error($second);
            $point = $second * $second_rate;
        }
		return $point;
	}

	/**
     * 待生成列表
     * @return array
     */
    public static function getTobeList() {
        $list = self::query(self::$table)
            ->leftJoin('order o', 'o.video_id = a.id')
            ->leftJoin('video v', 'v.id = a.video_id')
            ->_equal('a.member_id#member_id')
            ->where(['a.status' => 0])
            ->order('a.id desc')
            ->field('a.*,v.title,o.order_no')
            ->_page();
        return $list;
    }

    public static function update(array $array, array $array1)
    {
        self::model()->_update(self::$table, $array1, $array);
    }

}
